<template>
  <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      style="background:white;padding:20px;height:312px;"
  ><div style="text-align:left;height:50px;line-height:50px;"><i class="el-icon-user-solid">登录/注册</i></div>
    <el-form-item  prop="mobile">
      <el-input size="medium" v-model="ruleForm.mobile" placeholder="请输入手机号"></el-input>
    </el-form-item>
    <el-form-item  prop="code">
      <el-input   size="medium"  @keyup.enter.native="submitForm('ruleForm')" v-model="ruleForm.code" placeholder="请输入验证码">
        <el-button style="width:95px;padding: 0 10px" v-if="sending" slot="append" @click="getCode">获取验证码</el-button>
        <el-button v-else slot="append" :disabled="disabled">{{second}}秒后获取</el-button>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button style="width:100%" size="medium"  type="primary" @click="submitForm('ruleForm')">登录/注册</el-button>
    </el-form-item>
    <el-form-item class="user-policy">
      <el-checkbox style="display:inline-block;float: left;" v-model="checked"></el-checkbox>已阅读并同意《用户协议》和《隐私政策》
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "PhoneLogin",
  data() {
    const validate_mobile = (rule, value, callback) => {
      let reg = /^[1]([3-9])[0-9]{9}$/;
      if (!value) {
        callback("请输入手机号");
      } else if (!reg.test(value)) {
        callback("请输入正确的手机号");
      } else {
        callback();
      }
    };
    return {
      rules: {
        mobile: [{ required: true, validator: validate_mobile, trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      ruleForm:{
        mobile:'',
        code:''
      },
      sending: true,    //是否发送验证码
      disabled: false,  //是否禁发验证码
      second:59,        //倒计时间
      checked: false
    };
  },
methods:{  //methods

  //倒计时
  timeDown() {
    let result = setInterval(()=>{
      --this.second;
      if(this.second < 0) {
        clearInterval(result);
        this.sending  = true;
        this.disabled = false;
        this.second = 59;
      }
    }, 1000);
  },

  //获取验证码
  getCode(){
    if(!this.sending){
      return;
    }
    if(this.ruleForm.mobile == ''){
      this.$message.error('请输入手机号')
    }else{
      //api接口封装请求
      this.$http.user.getCode({
        mobile:this.ruleForm.mobile
      }).then(()=>{
        this.sending  = false;
        this.disabled = true;
        this.timeDown();
      })
    }
  },
  //提交
  submitForm(formName) {
    this.$refs[formName].validate(valid => {
      if (valid) {
        console.log('提交')
      }
    });
  }
}
}
</script>

<style scoped>
/deep/ .user-policy .el-form-item__content{
  line-height:20px;
}
</style>